package com.example.graphic.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.graphic.entity.User;
import com.example.graphic.mapper.UserMapper;
import com.example.graphic.service.UserService;
import org.springframework.stereotype.Service;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 用户业务实现
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    /**
     * 对密码进行 SHA-256 哈希
     */
    private String hashPassword(String raw) {
        return DigestUtil.sha256Hex(raw);
    }

    @Override
    public boolean register(String username, String password, String email) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        long count = this.count(wrapper);
        if (count > 0) {
            throw new RuntimeException("用户名已存在");
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(hashPassword(password));
        user.setEmail(email);
        user.setStatus(1);
        user.setCreatedTime(LocalDateTime.now());
        try{
            save(user);
        }catch (Exception e){
            e.printStackTrace();
            return  false;
        }

        return true;
    }

    @Override
    public User login(String username, String password) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        User user = this.getOne(wrapper, false);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        if (!Objects.equals(user.getPassword(), hashPassword(password))) {
            throw new RuntimeException("密码错误");
        }
        // 返回前隐藏密码
        user.setPassword(null);
        return user;
    }
} 